#define AIC_RUNTIME_EXPORTS
#include "../common/aic_runtime.h"
#include <cstdlib>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>

// 简单的线程池实现（占位）
class ThreadPool {
public:
    ThreadPool(size_t num_threads = std::thread::hardware_concurrency()) {
        for (size_t i = 0; i < num_threads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(queue_mutex);
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) return;
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }
    
    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (auto& worker : workers) {
            if (worker.joinable()) worker.join();
        }
    }
    
    void enqueue(std::function<void()> task) {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            tasks.push(std::move(task));
        }
        condition.notify_one();
    }
    
private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop = false;
};

static ThreadPool* g_thread_pool = nullptr;

extern "C" {

int aic_rt_init() {
    if (!g_thread_pool) {
        g_thread_pool = new ThreadPool();
    }
    return 0;
}

int aic_rt_shutdown() {
    if (g_thread_pool) {
        delete g_thread_pool;
        g_thread_pool = nullptr;
    }
    return 0;
}

int aic_rt_alloc_host(AIC_Buffer* out, size_t size) {
    if (!out) return -1;
    void* p = std::malloc(size);
    if (!p) return -2;
    out->ptr = p;
    out->size = size;
    return 0;
}

int aic_rt_free_host(AIC_Buffer* buf) {
    if (!buf || !buf->ptr) return -1;
    std::free(buf->ptr);
    buf->ptr = nullptr;
    buf->size = 0;
    return 0;
}

int aic_rt_submit_cpu() {
    if (!g_thread_pool) {
        return -1;
    }
    
    // TODO: 实际提交任务到线程池
    // g_thread_pool->enqueue([]{
    //     // 执行生产者分区（WG0）
    //     // 执行消费者分区（WG1）
    // });
    
    return 0;
}

int aic_rt_submit_spirv() {
    // CPU 运行时不支持 SPIR-V
    return -1;
}

}
